package cn.appsys.controller.deve;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.monitor.FileEntry;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import cn.appsys.constants.Constants;
import cn.appsys.pojo.AppInfo;
import cn.appsys.pojo.AppVersion;
import cn.appsys.pojo.DevUser;
import cn.appsys.service.deve.AppInfoService;
import cn.appsys.service.deve.AppVersionService;
import cn.appsys.service.deve.AppVersionServiceImpl;

@Controller
@RequestMapping("/deve/appversion")
public class AppVersionController {

	@Resource
	private AppInfoService appInfoService;
	
	@Resource
	private AppVersionService appVersionService;
	
	//用来保存新增的版本信息
	@RequestMapping(value="/addversionsave",method=RequestMethod.POST)
	public String addversionsave(AppVersion appVersion,
			@RequestParam("a_downloadLink")MultipartFile attach,Model model,
			HttpServletRequest request){
		String downLoadLink = "";    //用来保存apk文件的下载链接(当前apk文件的相对路径)
		String apkLocPath = "";      //用来保存上传的apk文件的绝对路径
		String apkFileName = "";     //用来保存apk文件的名字
		if(!attach.isEmpty()){
			//得到当前项目在tomcat上的发布目录+statics+uploadfiles  他们的绝对路径
			String path = request.getSession().getServletContext().getRealPath("statics\\uploadfiles");
			String oldFileName = attach.getOriginalFilename();   //得到上传的apk原文件名
			String extension = FilenameUtils.getExtension(oldFileName);  //得到上传的apk文件的后缀名
			if(extension.equalsIgnoreCase("apk")){
				//如果当前上传的文件其后缀为apk，即认为合法文件
				AppInfo appInfo = appInfoService.queryById(appVersion.getAppId());
				String newFileName = appInfo.getAPKName() + "-" + appVersion.getVersionNo() + ".apk";
				//创建File对象
				File file = new File(path,newFileName);
				if(!file.exists()){
					//判断在tomcat的发布目录下的statics/uploadfiles/目录下是否存在apkFileName
					file.mkdirs();
				}
				try {
					attach.transferTo(file); //进行最后的文件上传
				} catch (IllegalStateException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				//下载链接(apk文件的相对路径)
				downLoadLink = request.getContextPath() + "\\statics\\uploadfiles\\" + apkFileName;
				//apk文件在tomcat服务器的绝对路径
				apkLocPath = path + "\\" + apkFileName;
			}else{
				model.addAttribute("fileUploadError", "你上传的文件格式不正确，正确的格式为apk");
				
			}
		}
		
		//得到当前登录对象
		DevUser user = (DevUser)request.getSession().getAttribute(Constants.DEV_USER_SESSION);
		appVersion.setCreatedBy(user.getId());  //以当前登录用户对象的id作为当前新增版本的创建者id
		appVersion.setCreationDate(new Date()); //当前版本新增的时间
		appVersion.setDownloadLink(downLoadLink); //下载链接
		appVersion.setApkFileName(apkFileName);   //apk文件名
		appVersion.setApkLocPath(apkLocPath);    //apk文件上传的绝对路径
		//调用service的新增版本方法实现最终的新增，insertAppVersion方法返回值为新增的app版本的主键id
		try{
			int result = appVersionService.insertAppVersion(appVersion);
			if(result > 0){
				//获取到了在新增当前app版本后的主键id，之后还要将app_info表中version_id的值进行修改
				AppInfo appInfo = new AppInfo();
				appInfo.setId(appVersion.getAppId());
				appInfo.setVersionId(appVersion.getId());      //设置当前appInfo的最新版本
				int row = appVersionService.updateLogoPathById(appInfo);
				if(row > 0){
					return "redirect:/deve/appinfo/list";   //新增成功后，跳转到app信息列表页面
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		//如果新增失败，就跳回到app版本新增页面
		return "redirect:/deve/appversion/appversionadd/" + appVersion.getAppId();
	}
	/**
	 * 负责跳转到新增app版本页面appversionadd.jsp，在跳转过去之前，还要将当前app的历史版本列表信息查询出来
	 * @param appId app的主键id，可以通过app的主键id去查询当前app的历史版本列表信息
	 * @return
	 */
	@RequestMapping(value="/appversionadd/{id}")
	public String appVersionadd(@PathVariable("id")Integer id,Model model){
		//可以通过app的主键id去查询当前app的历史版本列表信息
		List<AppVersion> appVersionList = appVersionService.getAppVersionById(id);
		
		AppVersion appVersion = new AppVersion();
		appVersion.setAppId(id);
		
		model.addAttribute("appVersionList", appVersionList);
		model.addAttribute("appVersion", appVersion);
		return "developer/appversionadd"; //跳转到developer目录下的appversionadd.jsp中
	}
}
